<?php
/**
 * Created by PhpStorm.
 * User: ycbwl
 * Date: 2018/11/11
 * Time: 8:39 PM
 */
namespace app\api\service;

use app\api\model\Order as OrderModel;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Log;
use think\Loader;

//Loader::import();
//require_once "../../../extend/WxPay/WxPay.Api.php";
include APP_PATH."extend/WxPay/WxPay.Api.php";

class Pay{

    private $orderID;
    private $orderNo;

    public function __construct($orderID)
    {
        if(!$orderID){
            throw  new Exception('订单号不允许为空！');
        }
        $this->orderID = $orderID;
    }

    public function pay(){
        $this->checkOrderValid();
        $orderServer =  new Order();
        $status = $orderServer->checkOrderStock($this->orderID);
        if(!$status['pass']){
            return $status;
        }
        return  $this->makeWxPreOrder($status['orderPrice']);

    }


    private function makeWxPreOrder($totalPrice){
        $openid = Token::getCurrentTokenVar('openid');
        if(!$openid){
            throw new TokenException();
        }
        $wxOrderData = new \WxPayUnifiedOrder();
        $wxOrderData->SetOut_trade_no($this->orderNo);
        $wxOrderData->SetTrade_type('JSAPI');
        $wxOrderData->SetTotal_fee($totalPrice*100);
        $wxOrderData->SetBody("微信小程序支付");
        $wxOrderData->SetOpenid($openid);
        $wxOrderData->SetNotify_url('');
        return $this->getPaySignature($wxOrderData);
    }


    private function getPaySignature($wxOrderData){
        $wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
        if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS'){
            Log::init([
                'type'=>'File',
                'path'=>'',
                'level'=>['error']
            ]);
            Log::write('获取预支付订单失败','error');
            throw new Exception($wxOrder['return_msg']);
        }
        $this->recordPreOrder($wxOrder);
        $signature = $this->sign($wxOrder);
        return $signature;
    }


    private  function sign($wxOrder){
        $jsApiPayData = new \WxPayJsApiPay();
        $jsApiPayData->SetAppid(config("wx.app_id"));
        $jsApiPayData->SetTimeStamp((String)time());
        $rand = md5(time().mt_rand(0,1000));
        $jsApiPayData->SetNonceStr($rand);
        $jsApiPayData->SetPackage('prepay_id='.$wxOrder['prepay_id']);
        $jsApiPayData->SetSignType('md5');
        $sign = $jsApiPayData->MakeSign();
        $rawValues = $jsApiPayData->GetValues();
        $rawValues['paySign'] = $sign;
        unset($rawValues['appId']);
        return $rawValues;
    }

    private function recordPreOrder($wxOrder){
        OrderModel::where("id",$this->orderID)->update(['prepay_id'=>$wxOrder['prepay_id']]);
    }



    private function checkOrderValid(){
        $order = OrderModel::where("id",$this->orderID)->find();
        if(!$order){
            throw  new OrderException();
        }
        if(!Token::isValidOperate($order->user_id)){
            throw new TokenException([
                'msg'=>'订单与用户不匹配',
                'eerorCode'=>10003
            ]);
        }
        if($order->status != OrderStatusEnum::UNPAID){
            throw new OrderException([
                'msg'=>'订单状态错误，支付失败！'
            ]);
        }
        $this->orderNo = $order->order_no;
        return true;
    }

}